//Component Object
import { request,uploadFile2,getAliOssToken } from '../../utils/request.js'
import {
  throttle,
  isLogin,
  getAuthSetting,
  openSettingModal,
  getAudioUrl,
  formatSeconds
} from '../../utils/util.js'

const getToken = require('../../aliUtils/token.js').getToken
const SpeechTranscription = require('../../aliUtils/st.js')
const AKID = 'LTAI5tEiVB1fqnVmo2ctMYi2'
const AKKEY = '1USsGGtonGOgPvSNj71kefjTxDT6I7'
const aliSpeechUrl = 'wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1'
const APPKEY = '8w519vsOlGEdq8LH'
const app = getApp()
let canInvokeTimeUpdateFn = true
// 创建播放器
let _audioContext = null
// 已经播放过的音频地址
let playedAudioSrc = {}

// 当前用户和机器人对话列表
let attachVideoContext = null
// 测评引导 接口返回结果
let guideEvaluationResult = null
// 测评回复 接口返回结果
let tempEvaluationResult = null

// 录音相关变量

let showRecordPopTimeHandler = null
let touchStartTimer = null
let st = null
let recordBannerRectTop = 0
let stResult = ''
let tempStResult = ''
let recorderManager = null
let isCancelRecord = false
let requestTimeHandler = null
let timeHander = null
let curSeconds = 0 
let topTotalSeconds = 60
let startRecordTimer = null
let getRecordBannerRectTimer = null
let stsFinished = false
// 是不是正在测评
let isInEvaluation = false

let whenReqSwiperIndex = 0  // 当发送请求时的swiperIndex
let noMoreVideos = false
// touch相关变量，用于区分，单击还是双击
let touchEndTime = 0
let touchStartTime = 0
let lastTapTime = 0  // 上一次点击时间
let lastTapTimeoutFunc = null  // 上一次点击的定时器
let shareMediaId = '' // 分享视频的mediaId
// 对话区触摸事件
let chatTouchStartY = 0
let chatTouchEndY = 0
let pageNum = 1
let pageSize = 4
// 用户最后一次输入语音url
let lastUserVoiceUrl = ''
let quickShowQuestionnaire = false
let playAudioTimer = null
let requestTask = null 
let aiOptimizeTimeHandler = null
Component({
  options: {
    pureDataPattern: /^_/ // 指定所有 _ 开头的数据字段为纯数据字段
  },
  pageLifetimes:{
    show: function(){
      console.log('show')
      pageNum = 1
      pageSize = 4
      let launchOptions = wx.getEnterOptionsSync()
      // console.log('launchOptions:',launchOptions)
      // getAliOssToken()
      if(launchOptions && launchOptions.query){
        shareMediaId = launchOptions.query.shareMediaId || ''
        quickShowQuestionnaire = launchOptions.query.quickShowQuestionnaire ==='1' || false
      }
      this.setData({
        hasLogin: isLogin() || false,
      })
      this.initAudio()
      app.globalData.hadInVideoSwiper = true
      this.getSettingStatus()
    },
    hide(){
      console.log('hide')
      // this.closeChatPart()
      this.destoryAudio()
      // this.resetVar()
      this.destoryRecordManger()
      this.cancelRequest()
      clearTimeout(aiOptimizeTimeHandler)
      
      // this.setData({
      //   _videoList:[],
      //   curSwiperIndex:0,
      //   hasLogin: isLogin(),
      //   activeVideoList:[]
      // })
      // this.initCurPageVar()
      
    }
  },
  data: {
    curQuestionnaireTitle:'',
    circular: true,
    _videoList: [], // 总的视频列表
    curSwiperIndex: 0,
    hasLogin: isLogin() || false,
    hasRecordAuth: false,
    chatPartVisible: false,
    activeVideoList: [], // 当前播放或者待播放的视频列表
    _curVideoIndex: 0, // 当前播放的视频索引
    activeVideo: null, // 当前正在播放的视频对象
    _lastSwiperIndex: 0, // 上一个swiper索引
    _lastAnimationSwiperIndex: 0, // 上一个swiper索引
    isGiveTheUp: false, // 当前视频是否点赞
    isFav: false, // 当前视频是否收藏
    _videoWatched: 0, // 0表示视频没有看过，1表示看过
    _videoContextList: [],
    isVideoPlaying: false, // 是否正在播放
    loginDialogVisible: false,
    isMuted: false,
    // 对话区语音相关 对话状态，null，没语音，pending，请求中，completed，请求完成
    _curAudioOwner: 'ai', // visitor 当前播放的音频是机器人还是用户
    aiChatStatus: 'completed',
    visitorChatStatus: null,
    _curAiAudioSrc:'',
    _curVisitorAudioSrc:'',
    curAiAudioDuration: 0, // 当前机器人的音频时长
    curVisitorAudioDuration: 0, // 当前游客的音频时长
    isAiAudioPlaying: false, // 当前机器人的音频是否正在播放
    isVisitorAudioPlaying: false, // 当前机器人的音频是否正在播放
    
    // 展示内容
    attachContentVisible: false, // 展示内容
    attachContent:{},
    attachVideoIsPlaying: false, // 展示视频是否播放
    isAttachVideoMuted: true,
    // 录音相关
    recordProgressVisible: false,
    willCancelRecord:false,
    _inRecord: false,
    _recordType: 1, // _recordType: 1, // 1实时录音，2录音文件
    _aliToken: '',
    _audioServerPath:'',
    countTimeNum:11,
    showPureTime:true,
    curTimeStr:formatSeconds(curSeconds),
    limitTimeStr:formatSeconds(topTotalSeconds),
    submitBtnBgWidth:'0%',
    isPerformQuestion:false  // 区分现在是不是展示题，如果是展示题，则禁止用户输入
  },
  created: function () {
    console.log('vieoSwiper created')
  },
  attached: function () {
    console.log('vieoSwiper attached')
    pageNum = 1
    this.getVideoList()
    
    // this.getSettingStatus()
    this.getAliStsToken()
    this.setData({
      hasLogin: isLogin() || false,
    })
  },
  moved: function () {
    console.log('moved')
  },
  detached: function () {
    console.log('vieoSwiper detached')
    this.resetVar()
    // this.closeChatPart()
    this.initCurPageVar()
    this.destoryRecordManger()
    this.cancelRequest()
    clearTimeout(aiOptimizeTimeHandler)
  },

  methods: {
    destoryRecordManger() {
      if(recorderManager){
        recorderManager.stop()
        recorderManager = null
      }
    },
    isCurTabVisible(){
      // 此时此时，是不是在显示此tab页
      let currentTab = wx.getStorageSync('currentTab')
      return currentTab == 1
    },
    resetVar(){
      // 清空所有定时器
      console.log('resetVar')
      if(_audioContext){
        _audioContext.src = ''
        _audioContext.pause()
        _audioContext = null
      }
      if (recorderManager) {
        // console.log('recorderManager:',recorderManager)
        recorderManager.stop()
        recorderManager = null
      }
      if(attachVideoContext){
        attachVideoContext.destroy()
        // attachVideoContext.pause()
        attachVideoContext = null
      }
      if(st){
        try {
          st.close()
          st = null
        } catch (error) {
          console.log('close st error:',error)
        }
      }
      canInvokeTimeUpdateFn = touchStartTimer
      showRecordPopTimeHandler = null
      touchStartTimer = null
      recordBannerRectTop = 0
      stResult = ''
      tempStResult = ''
      recorderManager = null
      isCancelRecord = false
      requestTimeHandler = null
      timeHander = null
      curSeconds = 0 
      topTotalSeconds = 60
      startRecordTimer = null
      stsFinished = false
      getRecordBannerRectTimer = null
      noMoreVideos = false
      chatTouchStartY = 0
      chatTouchEndY = 0
      pageNum = 1
      pageSize = 4

      this.setData({
        _videoList:[],
        curSwiperIndex:0,
        chatPartVisible:false,
        activeVideoList:[],
        _curVideoIndex:0,
        activeVideo:null,
        _lastSwiperIndex:0,
        _lastAnimationSwiperIndex:0,
        isGiveTheUp:false,
        isFav:false,
        _videoWatched:0,
        _videoContextList:0,
        isVideoPlaying:false,
        isMuted:false,
        _curAudioOwner:'ai',
        aiChatStatus: 'completed',
        visitorChatStatus: null,
        _curAiAudioSrc:'',
        _curVisitorAudioSrc:'',
        curAiAudioDuration: 0, // 当前机器人的音频时长
        curVisitorAudioDuration: 0, // 当前游客的音频时长
        isAiAudioPlaying: false, // 当前机器人的音频是否正在播放
        isVisitorAudioPlaying: false, // 当前机器人的音频是否正在播放
        
        // 录音相关
        recordProgressVisible: false,
        willCancelRecord:false,
        _inRecord: false,
        _recordType: 1, // _recordType: 1, // 1实时录音，2录音文件
        _aliToken: '',
        _audioServerPath:'',
        countTimeNum:11,
        showPureTime:true,
        curTimeStr:formatSeconds(curSeconds),
        limitTimeStr:formatSeconds(topTotalSeconds),
        submitBtnBgWidth:'0%',
        isPerformQuestion:false 
      })
    },
    chatTouchStart(e){
      // console.log('chatTouchStart e:',e)
      chatTouchStartY = e.touches[0].pageY
    },
    chatTouchEnd(e){
      // console.log('chatTouchEnd e:',e)
      chatTouchEndY = e.changedTouches[0].pageY
      if(chatTouchEndY - chatTouchStartY > 10){
        console.log('对话区向下滑动')
        this.closeChatPart()
      }
    },
    initCurPageVar(){
      // 清空所有定时器
      clearTimeout(getRecordBannerRectTimer)
      clearTimeout(startRecordTimer)
      clearTimeout(requestTimeHandler)
      clearTimeout(timeHander)
      clearTimeout(showRecordPopTimeHandler)
      clearTimeout(touchStartTimer)
      clearTimeout(playAudioTimer)
      guideEvaluationResult = null
      tempEvaluationResult = null
      isInEvaluation = false
      app.globalData.isInEvaluation = false
      this.setData({
        aiChatStatus:'completed',
        _curAiAudioSrc:'',
        curAiAudioDuration:'',
        _curVisitorAudioSrc:'',
        visitorChatStatus:null,
        attachContentVisible:false,
        isPerformQuestion:false,
        curQuestionnaireTitle:''
      })
      app.globalData.curQuestionnaireTitle = ''
      setTimeout(()=>{
        this.setData({
          isMuted:false
        })
      },0)
    },
    selfShowToast(txt){
      wx.showToast({
        title:txt,
        icon:'none',
        duration:3000
      })
    },
    initRecordManager() {
      console.log('initRecordManager')
      let that = this
      if (!recorderManager) {
        recorderManager = wx.getRecorderManager()
      }
  
      recorderManager.onFrameRecorded(async (res) => {
        // console.log('onFrameRecorded:')
        if (res.isLastFrame) {
          // console.log('recorderManager isLastFrame')
          // 录音超时
          // this.completeRecord()
        }
  
        if (st && this.data._inRecord) {
          // console.log('send ' + res.frameBuffer)
          try {
            st.sendAudio(res.frameBuffer)  
          } catch (error) {
            console.log('st.sendAudio error:',error)
          }
        }
      })
      // 录音结束
      recorderManager.onStop(async (res) => {
        // console.log('recorderManager onStop isCancelRecord:',isCancelRecord)
        
        // 如果是取消的，直接返回，不做任何操作
        if (isCancelRecord) {
          return
        }
        // console.log('curSeconds:',curSeconds)
        // 录音时间太短
        // if (curSeconds < 2) {
        //   that.selfShowToast('录音时间太短了')
        //   return
        // }
        // console.log('录音结束 res:', res)
        // 正常提交
        if (res.tempFilePath) {
          let uploadResUrl = await uploadFile2(res.tempFilePath)
          // console.log('uploadResUrl :', uploadResUrl)
          // console.log('curSeconds :', curSeconds)
          that.setData({
            _audioServerPath: uploadResUrl,
          })
          // 如果是录音文件则直接提交，如果是实时录音，还要获取录音结果再提交
          // 录音文件
          if (this.data._recordType === 2) {
            that.submitRecordResult()
          } else {
            // that.startAiOptimize()
            // 等当前任务结束之后再操作
            // wx.showLoading({
            //   title: '发送中',
            //   mask: true
            // })
            this.setData({
              visitorChatStatus:'pending',
              curVisitorAudioDuration:curSeconds
            })
            // 1s后开始提交
            clearTimeout(aiOptimizeTimeHandler)
            aiOptimizeTimeHandler = setTimeout(() => {
              that.startAiOptimize()
            }, 1000)
          }
        }
      })
    },
    showRecordPop() {
      let that = this
      clearTimeout(showRecordPopTimeHandler)
      showRecordPopTimeHandler = setTimeout(() => {
        // console.log('showRecordPop setTimeout')
        that.setData({
          recordProgressVisible: true
        })
        that.getRecordBannerRect()
      },500)
    },
    async getRecordBannerRect() {
      if(getRecordBannerRectTimer !== null){
        return 
      }
      let that = this 
      // let that = this as any
      return new Promise((resolve) => {
        
        getRecordBannerRectTimer = setTimeout(()=>{
          wx.createSelectorQuery().in(that)
          .select('#recordBanner')
          .boundingClientRect(function (rect) {
            getRecordBannerRectTimer = null
            // console.log('getRecordBannerRect rect:',rect)
            // that.setData({
            //   recordBannerRect: rect
            // })
            if(rect){
              recordBannerRectTop = rect.top
              resolve( rect.top)
            }else {
             resolve(null)
            }
            
          })
          .exec()
        },1000)
        
      })
    },
    hideRecordPop() {
      console.log('hideRecordPop')
      clearTimeout(showRecordPopTimeHandler)
      this.setData({
        recordProgressVisible: false
      })
    },
    initRecordState() {
      console.log('initRecordState')
      // 把录音相关状态初始化
      curSeconds = 0
      stResult = ''
      tempStResult = ''
      this.setData({
        curTimeStr: formatSeconds(curSeconds),
        submitBtnBgWidth: '0%',
        showPureTime: true,
        countTimeNum: 11, // 倒计时提示显示的时间
        willCancelRecord: false
      })
      isCancelRecord = false
    },
    startRecordFile() {
      console.log('startRecordFile')
      if(!this.data._inRecord){
        console.log('点击太快')
        return 
      }
      // 初始化录音状态
      this.initRecordState()
      // 显示录音页面
      this.showRecordPop()
      // 开始录音文件
      clearTimeout(startRecordTimer)
      startRecordTimer = setTimeout(() => {
        this.startCountTime()
        // console.log('topTotalSeconds:',topTotalSeconds)
        recorderManager.start({
          duration: topTotalSeconds * 1000,
          sampleRate: 16000,
          format: 'mp3',
          frameSize: 4,
          encodeBitRate: 96000,
          numberOfChannels: 1
        })
      }, 0)
    },
    cancelRecord() {
      console.log('cancelRecord')
      isCancelRecord = true
      this.recordFinish()
    },
    stopCountTime() {
      if (timeHander) {
        clearInterval(timeHander)
      }
    },
    async recordFinish() {
      console.log('recordFinish')
      this.hideRecordPop()
      if (startRecordTimer) {
        clearTimeout(startRecordTimer)
      }
      // 只有实时录音才调用stop
      if (recorderManager) {
        recorderManager.stop()
      }
      if (!this.data._inRecord) {
        return
      }
  
      // 停止计时
      this.stopCountTime()
      // 录音结束
  
      this.setData({
        countTimeNum: 11,
        showPureTime: true,
        _inRecord: false
      })
      
      if (st && st._client) {
        // console.log('recordFinish st close：',st)
        // 延时关闭，避免数据还在传输中就被突然关闭
        try{
          setTimeout(() => {
            st.close()
          }, 500)
        }catch(e){
          console.log('recordFinish st close error:',e)
        }
        
      }
      // 删除录音并发
      // this.removeRecordConCurrent()
      // 录音文件直接关闭弹层
      // console.log('recordFinish 类型和时间:',this.data._recordType,curSeconds)
     
      try {
        // @ts-ignore
        wx.setPageStyle({
          style: {
            overflow: 'auto' // ‘auto’
          }
       })
      } catch (error) {
        
      }
    },
    removeRecordConCurrent() {
      let openid = wx.getStorageSync('openid')
      if (openid) {
        // 获取录音并发
        request({
          url: '/records/remove-real-time?key=' + openid,
          method: 'post',
          success(data) {
            console.log('删除录音并发')
          },
          fail(error) {
            console.log('删除录音并发失败：', error)
          }
        })
      }
    },
  
    startAiOptimize() {
      let that = this
      if (isCancelRecord) {
        wx.hideLoading()
        that.hideRecordPop()
        return
      }
      if (stResult === '' && tempStResult === '') {
        stsFinished = false
      }
      that.submitRecordResultRealTime()
  
    },
    submitRecordResult() {
      let that = this
      if (!requestTimeHandler) {
        requestTimeHandler = setTimeout(() => {
          requestTimeHandler = null
        }, 1000)
        this.userInput(content,2,this.data._audioServerPath)
        requestTimeHandler = null
        that.hideRecordPop()
      }
    },
    submitRecordResultRealTime() {
      // console.log('requestTimeHandler:',requestTimeHandler)
      // console.log('submitRecordResultRealTime:',stResult,this.data._audioServerPath)
      let that = this
      if (!requestTimeHandler) {
        requestTimeHandler = setTimeout(() => {
          requestTimeHandler = null
        }, 100)
        // this.stopAllAudio()
        // 如果录音转文字完成了，就用文本，否则用音频
        let contentType = stsFinished ? 1 : 2
        this.userInput(stResult,contentType,this.data._audioServerPath)
        requestTimeHandler = null
        that.hideRecordPop()
        wx.hideLoading()
      }
    },
    async mainTouchEnd(event) {
      let that = this
      clearTimeout(showRecordPopTimeHandler)
      clearTimeout(touchStartTimer)
      // console.log('mainTouchEnd this.data._inRecord:',this.data._inRecord)
      if (event.target.id === 'authRecordBtn'  && that.data._inRecord) {
        // 马上隐藏录音弹窗
        this.hideRecordPop()
        if (!recordBannerRectTop) {
          await that.getRecordBannerRect()
        }
        // console.log('recordBannerRectTop:',recordBannerRectTop)
        if (!recordBannerRectTop) {
          // @ts-ignore
          that.selfShowToast('录音时间太短了')
          this.cancelRecord()
          return
        }
        let touch = event.changedTouches[0]
        let pageY = touch.pageY
        // console.log('pageY:',pageY,',recordBannerRect.top:',recordBannerRect.top)
  
        if (pageY < recordBannerRectTop) {
          this.cancelRecord()
        } else {
          this.recordFinish()
        }
      }
    },
  
    async mainTouchMove(event) {

      if(!this.data.recordProgressVisible){
        return 
      }
      // console.log('mainTouchMove:',event)
      let that = this
      // console.log('mainTouchMove:',event.target.id,)
      if (event.target.id === 'authRecordBtn' && that.data._inRecord) {
        
        if (!recordBannerRectTop) {
          await that.getRecordBannerRect()
        }
        // console.log('mainTouchMove recordBannerRectTop:',recordBannerRectTop)
        if(!recordBannerRectTop){
          return
        }
        let touch = event.touches[0]
        let pageY = touch.pageY
        if (pageY < (recordBannerRectTop - 20)) {
          that.setData({
            willCancelRecord: true
          })
        } else {
          that.setData({
            willCancelRecord: false
          })
        }
      }
    },
    catchTouchEnd() {
      // console.log('catchTouchEnd')
      return
    },
    catchTouchMove() {
      return
    },
    // ai语音相关
    // 聊天搜索
    aiSearchChat(content,contentType,contentUrl) {
     
      this.setData({
        isPerformQuestion:false,
        curQuestionnaireTitle:''
      })
      app.globalData.curQuestionnaireTitle = ''
      let activeVideo = this.data.activeVideo
      let reqData = {
        content,
        contentType,
        contentUrl,
        dialogueContentId:activeVideo.dialogueContent.dialogId,
        resourceId: activeVideo.mediaId,
        resourceType:1
      }
      console.log('aiSearchChat reqData:',reqData)
      this.cancelRequest()
      requestTask = request({
        url: '/api/questionnaireLaunch/chatOrSearch',
        method: 'POST',
        data: reqData,
        success: (respData,data) => {
          console.log('aiSearchChat respData:',respData)
          console.log('aiSearchChat respMsg:',data.respMsg)

          if(whenReqSwiperIndex !== this.data.curSwiperIndex){
            return 
          }
          
          if(respData.type == 1) {
            // 返回语音
            this.playAudio(respData.content,'ai')
          }else if(respData.type == 2){
            // 返回视频
            wx.setStorageSync('busMedia', respData.busMedia)
            wx.navigateTo({
              url:'/pages/videoList/videoList'
            })
          }
        },
        complete:()=>{
          this.setData({
            aiChatStatus: 'completed',
          })
        }
      })
    },
    // 测评引导
    async aiAssessGuide(content, contentType=1,contentUrl) {
      this.hideQuestionAttachContent()
      this.setData({
        isPerformQuestion:false,
        aiChatStatus:'pending'
      })
      let activeVideo = this.data.activeVideo
      // console.log('videoSwiper aiAssessGuide activeVideo:',activeVideo)
      // 有上一次返回的结果
      let reqData ={
        content,
        contentType,
        contentUrl,
      }
      if(guideEvaluationResult){
        reqData = {
          ...guideEvaluationResult,
          ...reqData
        }
      }else {
        reqData = {
          ...reqData,
          dialogueContentId:activeVideo.dialogueContent.dialogId,
          questionnaireId: activeVideo.dialogueContent.questionnaireId,
          resourceId: activeVideo.mediaId,
          resourceType:1,
          type: 1,
          workflowStatus: 1
        }
      }
      console.log('aiAssessGuide reqData:',reqData)
      this.cancelRequest()
      requestTask = request({
        url: '/api/questionnaireLaunch/guideEvaluation',
        method: 'POST',
        data: reqData,
        success: (respData,data) => {
          console.log('whenReqSwiperIndex:',whenReqSwiperIndex)
          if(whenReqSwiperIndex !== this.data.curSwiperIndex){
            return 
          }
          console.log('aiAssessGuide respData:',respData)
          console.log('aiAssessGuide respMsg:',data.respMsg)
          guideEvaluationResult = respData
          // 返回内容
          // 判断下个用户输入是否需要跳转到测评
          if(respData.workflowStatus ===2){
            isInEvaluation = true
            app.globalData.isInEvaluation = true
            this.setData({
              curQuestionnaireTitle:respData.questionnaireTitle
            })
            app.globalData.curQuestionnaireTitle = respData.questionnaireTitle
            // console.log('respData.workflowStatus:',respData.workflowStatus)
            // this.aiAssess(content, contentType,contentUrl,respData)
            
          }else if(respData.workflowStatus ===1){
            isInEvaluation = false
            app.globalData.isInEvaluation = false
            this.setData({
              curQuestionnaireTitle:''
            })
            app.globalData.curQuestionnaireTitle = ''
          }
          // 现在是不是展示题，如果是展示题，则禁止用户输入
          if(respData.questions && respData.questions.questionType ==5){
            // 展示题
            this.setData({
              isPerformQuestion:true
            })
            
          }else {
            this.setData({
              isPerformQuestion:false
            })
            
          }

          // 显示展示内容
          this.showQuestionAttachContent(respData)
          
          this.playAudio(respData.content,'ai')
          // 播放返回的语音
          if(respData.doneFlag){
            console.log('整个流程结束了，不用再往下走了')
          }
        },
        fail: (data) => {
          console.log('aiAssessGuide err:',data)
          if(data.respCode === 401){
            this.showLoginDialog()
          }
        },
        complete:()=>{
          this.setData({
            aiChatStatus: 'completed',
          })
        }
      })
    },
    // 测评
    async aiAssess(content, contentType=1,contentUrl,guideRespData) {
      // console.log('start aiAssess',content, contentType,contentUrl)
      
      let reqData = {
        content,
        contentType,
        contentUrl,
      }
      let activeVideo = this.data.activeVideo
      if(tempEvaluationResult){
        reqData = {
          ...tempEvaluationResult,
          ...reqData
        }
      }else if(guideEvaluationResult){
        reqData = {
          ...guideEvaluationResult,
          ...reqData
        }
      }else if(guideRespData){
        reqData = {
          ...guideRespData,
          ...reqData,
          
        }
      }else {
        reqData = {
          ...reqData,
          dialogueContentId:activeVideo.dialogueContent.dialogId,
          questionnaireId: activeVideo.dialogueContent.questionnaireId,
          resourceId: activeVideo.mediaId,
          resourceType:1,
          type: 1,
          workflowStatus: 1
        }
      }
      this.setData({
        aiChatStatus:'pending'
      })
      console.log('aiAssess reqData:',reqData)
      this.cancelRequest()
      requestTask = request({
        url:'/api/questionnaireLaunch/startQuestionnaire',
        method: 'POST',
        data: reqData,
        success:(respData,data)=>{
          console.log('whenReqSwiperIndex:',whenReqSwiperIndex)
         
          if(whenReqSwiperIndex !== this.data.curSwiperIndex){
            return 
          }
          console.log('aiAssess respData:',respData)
          console.log('aiAssess respMsg:',data.respMsg)
          tempEvaluationResult = respData
          if(reqData.workflowStatus ===2){
            isInEvaluation = true
            app.globalData.isInEvaluation = true
            this.setData({
              curQuestionnaireTitle:respData.questionnaireTitle
            })
            app.globalData.curQuestionnaireTitle = respData.questionnaireTitle
          }else if(reqData.workflowStatus ===1){
            isInEvaluation = false
            app.globalData.isInEvaluation = false
            this.setData({
              curQuestionnaireTitle:''
            })
            app.globalData.curQuestionnaireTitle = ''
          }
          if(respData.questions && respData.questions.questionType ==5){
            // 展示题
            this.setData({
              isPerformQuestion:true
            })
          }else {
            this.setData({
              isPerformQuestion:false
            })
          }
            
          // 返回内容
          // 播放返回的语音
         
          this.playAudio(respData.content,'ai')
          // 显示展示内容
          this.showQuestionAttachContent(respData)

          if(respData.doneFlag){
            this.setData({
              isPerformQuestion:false
            })
            console.log('整个流程结束了，不用再往下走了')
          }
        },
        complete:()=>{
          this.setData({
            aiChatStatus: 'completed',
          })
        }
      })
    },
    hideQuestionAttachContent() {
      this.setData({
        attachContentVisible: false
      })
    },
    jumpToWebPage(event){
      console.log('jumpToWebPage event:',event)
      let url = event.currentTarget.dataset.webUrl
      wx.navigateTo({
        url: '/pages/webview/webview?url='+url
      })
    },
    showQuestionAttachContent(respData){
      // 如果关闭了对话区，则直接返回
      if(!this.data.chatPartVisible){
        return 
      }
      // 展示默认题目
      if(!respData.questions){
        this.setData({
          attachContentVisible:false
        })
        return 
      }
      // if(respData.questionShows && respData.questionShows.length ===0){
      //   this.setData({
      //     attachContentVisible:true
      //   })
      //   return
      // }
      // nodeFlag 是false，就是没有新内容，则还是展示原来的内容
      // if(!respData.nodeFlag && this.data.attachContentVisible){
      //   return 
      // }
      if(respData.questions.showType === 0){
        this.setData({
          attachContent:{
            type:'question',
            questionShows: respData.questions.questionTitle
          }
        })
      }else if(respData.questions.showType === 1){
        // 多图
        this.setData({
          attachContent:{
            type:'imgs',
            questionShows: respData.questionShows
          }
        })
        
      }else if(respData.questions.showType === 2){
        // 视频
        this.setData({
          attachContent:{
            type:'video',
            questionShows: respData.questionShows[0]
          }
        },()=>{
          // console.log('attachContent:',this.data.attachContent)
          // this.playAttachedVideo()
        })
        
      }else if(respData.questions.showType === 3){
        // 网页
        this.setData({
          attachContent:{
            type:'web',
            questionShows: respData.questionShows
          }
        })
      }
      this.setData({
        attachContentVisible: true
      },()=>{
        // console.log('attachContent:',this.data.attachContent)
        this.stopCurSwiperVideo()
      })
    },
    userInput(content ='', contentType=1,contentUrl) {
      if(content===''){
        contentType = 2
      }
      whenReqSwiperIndex = this.data.curSwiperIndex
      console.log('userInput:',content,contentType,contentUrl)
      // 模拟用户语音输入信息
      // this.setData({
      //   visitorChatStatus: 'completed',
      //   _curVisitorAudioSrc: contentUrl,
      //   _curAudioOwner: 'visitor'
      // },()=>{
      //   this.playAudio(contentUrl,'visitor')
      // })
      // 用户输入不用主动播放
      this.stopAudio()
      let _curVisitorAudioSrc =  contentUrl || lastUserVoiceUrl
      this.setData({
        visitorChatStatus: _curVisitorAudioSrc ? 'completed': null,
        _curVisitorAudioSrc: _curVisitorAudioSrc,
        _curAudioOwner: 'visitor'
      })
      if(contentUrl){
        lastUserVoiceUrl = contentUrl
      }


      // this.playAudio(contentUrl,'visitor')
      let activeVideo = this.data.activeVideo
      
      
      // 有问卷
      if(activeVideo.dialogueContent.questionnaireId){
        // 如果引导结果存在，且要开启测评流程，则走测评流程
        if(isInEvaluation) {
          this.aiAssess(content, contentType,contentUrl)
        }else{
          // 继续走引导流程
          this.aiAssessGuide(content,contentType,contentUrl)
        }
        
      }else {
        // 无问卷,走搜索流程
        
        this.aiSearchChat(content,contentType,contentUrl)
      }
    },
    initAudio() {
      playedAudioSrc = {}
      _audioContext = wx.createInnerAudioContext()
      // console.log('_audioContext:',_audioContext)
      _audioContext.onCanplay(()=>{
        // console.log('_curAudioOwner:',this.data._curAudioOwner)
        console.log('swiper onCanplay _audioContext.duration:',_audioContext.duration)
        if(this.data._curAudioOwner === 'ai'){
          if(_audioContext.duration > 0){
            this.setData({
              curAiAudioDuration: Math.floor(_audioContext.duration)
            })
          }
        }
      })
      _audioContext.onTimeUpdate(()=>{
        
        // console.log('onTimeUpdate _audioContext.duration:',_audioContext.duration)
        if(this.data._curAudioOwner == 'ai'){
          
          this.setData({
            curAiAudioDuration: Math.floor(_audioContext.duration),
            isAiAudioPlaying:true
          })
        }else if(this.data._curAudioOwner == 'visitor'){
          this.setData({
            // curVisitorAudioDuration: Math.floor(_audioContext.duration),
            isVisitorAudioPlaying:true
          })
        }
      })
      // _audioContext.onPlay(()=>{
      //   console.log('_audioContext onPlay')
      //   if(_audioContext.duration > 0){
      //     this.setData({
      //       curAiAudioDuration: Math.floor(_audioContext.duration)
      //     })
      //   }
      // })
      _audioContext.onPause(()=>{
        // console.log('_audioContext onPause')
        this.setData({
          isAiAudioPlaying: false,
          isVisitorAudioPlaying: false
        })
      })
      _audioContext.onStop(()=>{
        // console.log('_audioContext onStop')
        this.setData({
          isAiAudioPlaying: false,
          isVisitorAudioPlaying: false
        })
      })
      _audioContext.onEnded(()=>{
        // console.log('_audioContext onEnded _curAudioOwner:',this.data._curAudioOwner)
        // if(this.data._curAudioOwner === 'ai'){
        //   let ans = '不知道哦'
        //   if(questionIndex ===0){
        //     ans = '苹果'
        //   }else if(questionIndex ===1){
        //     ans = '不知道'
        //   }else if(questionIndex ===2){
        //     ans = '8'
        //   }
        //   questionIndex++
        //   this.userInput(ans,1,'')
        // }
        // 如果当前是展示题，则播放完立马请求下一题
        if(this.data._curAudioOwner === 'ai' && this.data.isPerformQuestion){
          this.userInput('好的',1)
        }
        this.setData({
          isAiAudioPlaying: false,
          isVisitorAudioPlaying: false
        })
      })
    },

    async playAudio(audioUrl,type){
      console.log('playAudio:',audioUrl,type)
      // 如果对话区已经收起了，就不播放语音
      if(!this.data.chatPartVisible){
        return 
      }
      if(!audioUrl){
        return 
      }
      if(!this.data.isMuted){
        this.metedVideo()
      }
      let localSrc = audioUrl
      if(/^http/.test(audioUrl)){
        localSrc = playedAudioSrc[audioUrl]
        // console.log('inner localSrc:',localSrc)
        if(!localSrc){
          localSrc = await getAudioUrl(audioUrl)
          playedAudioSrc[audioUrl] = localSrc
        }
      }
      // console.log('localSrc:',localSrc)
      if(!/\.mp3/.test(localSrc)){
        console.log('localSrc not mp3')
        return 
      }
      
      _audioContext.stop()
      _audioContext.src = localSrc
      
      if(type ==='ai'){
        this.setData({
          _curAudioOwner: 'ai',
          aiChatStatus:'completed',
          _curAiAudioSrc: localSrc,
          isAiAudioPlaying: true,
          isVisitorAudioPlaying:false
        })
      }else if(type ==='visitor'){
        this.setData({
          _curAudioOwner: 'visitor',
          visitorChatStatus:'completed',
          isVisitorAudioPlaying:true,
          isAiAudioPlaying: false,
        })
      }else {
        this.setData({
          _curAudioOwner: type,
          isVisitorAudioPlaying:false,
          isAiAudioPlaying: false,
        })
      }
      // console.log('_audioContext will play')
      // clearTimeout(playAudioTimer)
      // playAudioTimer = setTimeout(()=>{
        
      // },300)
      _audioContext.play()
    },
    replayAiAudio(){
      if(this.data.aiChatStatus === 'completed'){
        if(this.data.isAiAudioPlaying){
          this.stopAudio()
        }else {
          let _curAiAudioSrc = this.data._curAiAudioSrc
          this.playAudio(_curAiAudioSrc,'ai')
        }
      }
      
      
    },
    replayCurVisitorAudio(){
      if(this.data.visitorChatStatus === 'completed'){
        if(this.data.isVisitorAudioPlaying){
          this.stopAudio()
        }else {
          let _curVisitorAudioSrc = this.data._curVisitorAudioSrc
          console.log('_curVisitorAudioSrc:',_curVisitorAudioSrc)
          this.playAudio(_curVisitorAudioSrc,'visitor')
        }
      }
      
      
    },
    stopAudio(){
      _audioContext && _audioContext.stop()
      this.setData({
        isAiAudioPlaying: false,
        isVisitorAudioPlaying: false
      })
    },
    destoryAudio(){
      console.log('destoryAudio')
      if(_audioContext){
        _audioContext.src = ''
        _audioContext.stop()
        _audioContext.destroy()
      }
      this.setData({
        isAiAudioPlaying: false,
        isVisitorAudioPlaying: false
      })
      
    },
    loginDialogClose() {
      this.setData({
        loginDialogVisible: false,
        hasLogin: isLogin()
      })
      
    },
    showLoginDialog() {
      this.stopAudio()
      this.setData({
        loginDialogVisible: true
      })
    },
    initVideoContext() {
      let _videoContext0 = wx.createVideoContext('video0', this)
      let _video1Context1 = wx.createVideoContext('video1', this)
      let _video2Context2 = wx.createVideoContext('video2', this)
      this.data._videoContextList = [
        _videoContext0,
        _video1Context1,
        _video2Context2
      ]
      // console.log('_videoContext0:',_videoContext0)
      // _videoContext0.play()
    },
    agreePrivacyAuthorization() {
      // 用户同意隐私协议
      console.log('用户同意隐私协议2')
    },
    closeChatPart() {
      this.setData({
        chatPartVisible: false,
        isMuted: this.data.attachContentVisible
      })
      this.stopAudio()
    },
    showChatPart() {
      
      this.setData({
        chatPartVisible: true,
        isMuted: true
      })
      let activeVideo = this.data.activeVideo
      let dialogVoice = activeVideo.dialogueContent.dialogVoice
      // console.log('dialogVoice:',dialogVoice)
      // 用户第一次打开点击对话区，播放当前视频的ai对话语音
      // 当前没有ai语音，才会自动播放第一条ai语音
   
      if(!this.data._curAiAudioSrc){
        if(dialogVoice){
          this.setData({
            _curAudioOwner: 'ai'
          },()=>{
            this.playAudio(dialogVoice,'ai')
          })
        }
      }
      
    },
    changeChatPartVisible() {
      
      // 对话区是打开的，则关闭
      if (this.data.chatPartVisible) {
        this.closeChatPart()
      }else {
        // 对话区是关闭的，则打开
        this.showChatPart()
      }
     
    },

    onLoadedMetaData() {
      // console.log('onLoadedMetaData')
    },
    // 首次进来时视频和语音需要执行的操作
    initVideoAndAudioAni(){
      let that = this
      let videoContext = this.data._videoContextList[this.data.curSwiperIndex]
      videoContext.play()
      let activeVideo = that.data.activeVideo
      // 如果存在需要立即展示问卷，则需要直接播放问卷
      if(quickShowQuestionnaire && activeVideo.dialogueContent && activeVideo.dialogueContent.questionnaireId){
        that.setData({
          chatPartVisible: true
        })
        setTimeout(()=>{
          that.aiAssessGuide('wanhujiankang11',1)  
        },0)
        
      }
    },
    getVideoList() {
      
      if(noMoreVideos){
        console.log('没有更多视频了')
        return 
      }
      var that = this
      let lastVideo = this.data._videoList[this.data._videoList.length - 1]
      let lastId = lastVideo && lastVideo.mediaId || ''
      let reqData = {
        pageSize,
        pageNum,
        mediaStatus: 1,
        lastId: lastId,
        shareMediaId:shareMediaId,
      }
      // console.log('getVideoList reqData:', reqData)
      request({
        url: '/api/BusMedia/recommend',
        data: reqData,
        method: 'GET',
        success: (respData) => {
          console.log('apppage respData:', respData)
          if (respData.length > 0) {
            let _videoList = that.data._videoList
            _videoList = _videoList.concat(respData)
            pageNum++
            that.setData({
              _videoList: _videoList
            })
            // console.log('_videoList:',_videoList)
            // console.log('activeVideoList:',this.data.activeVideoList)
            let activeVideo = _videoList[0]
            // 如果还没有视频，则初始化添加视频列表
            if (this.data.activeVideoList.length == 0) {
              // 初始化
              that.setData({
                activeVideoList: _videoList.slice(0, 3),
                activeVideo: activeVideo,
                isFav: activeVideo.isFav >= 1,
                isGiveTheUp: activeVideo.isClick >=1
              },()=>{
                that.initVideoContext()
                app.globalData.activeVideo = activeVideo
                // console.log('app.globalData.activeVideo:',app.globalData.activeVideo)
                // console.log('_videoContextList:', this.data._videoContextList)
                let isCurTabVisible = that.isCurTabVisible()
                // 如果当前是视频列表也在显示，则播放第一个视频
                if(isCurTabVisible){
                  that.initVideoAndAudioAni()
                }
                
              })
              
            }
          }else {
            noMoreVideos = true
          }
          
        }
      })
    },
   
    videoPlay() {
      // play和pause是异步的，有时候pause先触发，有时候play先触发，所以需要延时设置isVideoPlaying
      this.setData({
        isVideoPlaying: true
      })
      
    },

    continuePlaying() {
      console.log('continuePlaying')
      this.data._videoContextList[this.data.curSwiperIndex].play()
      this.setData({
        isVideoPlaying: true
      })
    },
    continuePlayAttachVideo(){
      if(this.data.isAttachVideoPlaying){

      }
    },
    playAttachedVideo() {
      this.stopCurSwiperVideo()
      // console.log('playAttachedVideo attachVideoContext:',attachVideoContext)
      if(!attachVideoContext){
        attachVideoContext = wx.createVideoContext('attachVideo',this)
      }
      // console.log('playAttachedVideo attachVideoContext2:',attachVideoContext)
      this.stopAudio()
      attachVideoContext.play()
      
    },
    attachVideoOnPlay(){
      // console.log('attachVideoOnPlay')
      this.setData({
        attachVideoIsPlaying: true
      })
    },
    stopCurSwiperVideo(){
      // console.log('_videoContextList:',this.data._videoContextList)
      let videoContext = this.data._videoContextList[this.data.curSwiperIndex]
      // console.log('videoContext:',videoContext)
      videoContext.pause()
      
      // this.data._videoContextList.forEach(videoContext => {
      //   videoContext.pause()
      // })
      this.setData({
        isVideoPlaying: false
      })
    },
    stopAttachVideo(){
      if(attachVideoContext){
        attachVideoContext.pause()
      }
      this.setData({
        attachVideoIsPlaying: false
      })
    },
    attachVideoTap(){
      // console.log('attachVideoTap')
      if(!attachVideoContext || attachVideoContext.paused){
        this.playAttachedVideo()
        
      }else {
        this.stopAttachVideo()
      }
    },
    videoTouchStart(e) {
      touchStartTime = e.timeStamp
    },
    /// 按钮触摸结束触发的事件
    videoTouchEnd(e) {
      touchEndTime = e.timeStamp
    },
    videoMultipleTap(e){
      let that = this
      // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
      if (touchEndTime - touchStartTime < 350) {
        // 当前点击的时间
        let currentTime = e.timeStamp
        
        
        // 如果两次点击时间在300毫秒内，则认为是双击事件
        if (currentTime - lastTapTime < 300) {
          // console.log("double tap")
          // 成功触发双击事件时，取消单击事件的执行
          clearTimeout(lastTapTimeoutFunc);
          that.videoDoubleTap()
        } else {
          // 单击事件延时300毫秒执行，这和最初的浏览器的点击300ms延时有点像。
          lastTapTimeoutFunc = setTimeout(function () {
            // console.log("tap")
            that.videoTap()
          }, 300);
        }
        lastTapTime = currentTime
      }
    },
    videoDoubleTap(){
      this.giveTheUp()
    },
    videoTap() {
      let videoContext = this.data._videoContextList[this.data.curSwiperIndex]
      if (videoContext.paused) {
        videoContext.play()
        this.setData({
          isVideoPlaying: true,
          attachVideoIsPlaying:false
        })
        this.stopAudio()
        if(attachVideoContext){
          attachVideoContext.pause()
        }
      } else {
        videoContext.pause()
        this.setData({
          isVideoPlaying: false
        })
      }
    },
    playCurSwiperVideo(){
      
      let videoContext = this.data._videoContextList[this.data.curSwiperIndex]
      console.log('playCurSwiperVideo videoContext:',videoContext)
      if (videoContext.paused) {
        videoContext.play()
        this.setData({
          isVideoPlaying: true,
          attachVideoIsPlaying:false
        })
        this.stopAudio()
        if(attachVideoContext){
          attachVideoContext.pause()
        }
      }
    },
    onTimeUpdate(e) {
      
      if (canInvokeTimeUpdateFn && this.data._videoWatched === 0 && isLogin()) {
        // console.log('onTimeUpdate')
        canInvokeTimeUpdateFn = false
        // 限制每2s调用1次，避免过快调用
        setTimeout(() => {
          canInvokeTimeUpdateFn = true
        }, 2000)
        let currentTime = e.detail.currentTime
        let duration = e.detail.duration
        if (currentTime / duration > 0.8) {
          this.setData({
            _videoWatched: 1
          })
          let activeVideo = this.data.activeVideo
          request({
            url: '/api/BusMediaPlayLog',
            method: 'POST',
            data: {
              client: 2,
              busMediaId: activeVideo.mediaId,
              mediaAccountId: activeVideo.mediaAccountId
            },
            success: (res) => {
              console.log('更新播放时长 res:', res)
            }
          })
        }
      }
    },
    //点赞
    giveTheUp() {
      console.log('giveTheUp')
      if (!isLogin()) {
        this.showLoginDialog()
        return
      }
      let activeVideo = this.data.activeVideo
      var that = this
      if (this.data.isGiveTheUp) {
        //已点赞状态，取消点赞
        request({
          url:
            '/api/BusMediaClick/deleteBusMediaId/' +
            activeVideo.mediaId +
            '/' +
            activeVideo.mediaAccountId,
          data: {
            token: wx.getStorageSync('token'),
            openId: wx.getStorageSync('userInfo').openId,
            client: 2,
            mediaAccountId: activeVideo.mediaAccountId,
            busMediaId: activeVideo.mediaId
          },
          method: 'DELETE',
          success: function () {
            let newClickCount = that.data.activeVideo.clickCount- 1
            if(newClickCount < 0){
              newClickCount = 0
            }
            that.setData({
              isGiveTheUp: false,
              ['activeVideo.clickCount']: newClickCount
            })
          }
        })
      } else {
        //未点赞状态，点赞
        request({
          url: '/api/BusMediaClick',
          data: {
            token: wx.getStorageSync('token'),
            openId: wx.getStorageSync('userInfo').openId,
            client: 2,
            mediaAccountId: that.data.activeVideo.mediaAccountId,
            busMediaId: that.data.activeVideo.mediaId
          },
          method: 'post',
          success: function () {
            let newClickCount = that.data.activeVideo.clickCount + 1
            that.setData({
              isGiveTheUp: true,
              ['activeVideo.clickCount']: newClickCount
            })
          },
          fail: () => {
            that.setData({
              isGiveTheUp: true
            })
          }
        })
      }
      // Notify('此功能正在开发~')
    },
    setCollectVideo(busMediaId, mediaAccountId) {
      request({
        url: '/api/BusMediaFav',
        data: {
          token: wx.getStorageSync('token'),
          busMediaId: busMediaId,
          client: 2, //小程序
          mediaAccountId: mediaAccountId
        },
        method: 'POST'
      })
    },
    deleteCollect(busMediaId, mediaAccountId) {
      console.log('deleteCollect')
      request({
        url:
          '/api/BusSubjectFav/deleteBusMediaId/' +
          busMediaId +
          '/' +
          mediaAccountId,
        data: {
          token: wx.getStorageSync('token'),
          busMediaId: busMediaId,
          client: 2, //小程序
          mediaAccountId: mediaAccountId
        },
        method: 'DELETE'
      })
    },
    //收藏
    collectVideo() {
      if (isLogin()) {
        let activeVideo = this.data.activeVideo
        var favCount = activeVideo.favCount
        if (this.data.isFav) {
          // 取消收藏
          favCount--
          this.deleteCollect(activeVideo.mediaId, activeVideo.mediaAccountId)
        } else {
          favCount++
          this.setCollectVideo(activeVideo.mediaId, activeVideo.mediaAccountId)
        }
        this.setData({
          isFav: !this.data.isFav,
          ['activeVideo.favCount']: favCount
        })
      } else {
        this.showLoginDialog()
      }
    },
    //判断当前视频点赞状态
    getVideoClickStatus() {
      if (isLogin()) {
        let that = this
        let activeVideo = this.data.activeVideo
        // console.log('activeVideo:', activeVideo)
        request({
          url:
            '/api/BusMediaClick/showIsAddClick/' +
            activeVideo.mediaId +
            '/' +
            activeVideo.mediaAccountId,
          method: 'GET',
          success: function (respData) {
            // console.log('hadAddToClick respData:', respData)
            that.setData({
              isGiveTheUp: respData.hadAddToClick
            })
          }
        })
      }
      
    },
    //判断当前视频收藏状态
    getVideoFavStatus() {
      if(isLogin()){
        const that = this
        let activeVideo = this.data.activeVideo
        
        request({
          url:
            '/api/BusMediaFav/showIsAddToFav/' +
            activeVideo.mediaId +
            '/' +
            activeVideo.mediaAccountId,
          method: 'get',
          success: function (respData) {
            that.setData({
              isFav: respData.hadAddToMyFav
            })
          }
        })
      }
      
    },

    swiperAnimationfinish: function (e) {
      
      // this.closeChatPart()
      let curSwiperIndex = e.detail.current
      let _lastAnimationSwiperIndex = this.data._lastAnimationSwiperIndex
      
      // console.log('swiperAnimationfinish curSwiperIndex:',curSwiperIndex)
      //  用户没有滑动成功，直接return，不执行
      if (_lastAnimationSwiperIndex === curSwiperIndex) {
        // console.log('swiperAnimationfinish return ')
        return
      }
      // 滑动成功，更新变量
      let _videoList = this.data._videoList
      let circular = true
      let _curVideoIndex = this.data._curVideoIndex
      // console.log('_curVideoIndex:',_curVideoIndex)
      // if (
      //   _curVideoIndex <= 0 ||
      //   _curVideoIndex >= _videoList.length - 1
      // ) {
      //   circular = false
      // } else {
      //   circular = true
      // }
      
      this.data._videoContextList.forEach((videoContext, index) => {
        if (index === curSwiperIndex) {
          this.setData({
            isMuted:false
          },()=>{
            videoContext.play()
          })
          
        } else {
          videoContext.pause()
        }
      })
      // circular 没有拦截成功，用户继续滑动了swiper
     
      // 当滑动到倒数第二个swiper时去请求新的video数据
      if (_curVideoIndex >= this.data._videoList.length - 2) {
        this.getVideoList()
      }
      // 视频列表
      let preVideoIndex = _curVideoIndex - 1
      let nextVideoIndex = _curVideoIndex + 1
      if (preVideoIndex < 0) {
        preVideoIndex = _videoList.length - 1
      }
      if (nextVideoIndex > _videoList.length - 1) {
        nextVideoIndex = 0
      }
      
      // 更新播放视频
      let preSwiperIndex = curSwiperIndex - 1
      let nextSwiperIndex = curSwiperIndex + 1
      if (preSwiperIndex < 0) {
        preSwiperIndex = 2
      }
      if (nextSwiperIndex > 2) {
        nextSwiperIndex = 0
      }
      let activeVideoList = this.data.activeVideoList
      activeVideoList[preSwiperIndex] = _videoList[preVideoIndex]
      activeVideoList[curSwiperIndex] = _videoList[_curVideoIndex]
      activeVideoList[nextSwiperIndex] = _videoList[nextVideoIndex]
    
      
      let activeVideo = _videoList[_curVideoIndex]
      if(!activeVideo.mediaAccountId){
        activeVideo.mediaAccountId = ''
      }
      app.globalData.activeVideo = activeVideo
      this.setData({
        _curVideoIndex: _curVideoIndex,
        activeVideoList: activeVideoList,
        circular: circular,
        activeVideo: activeVideo,
        _lastAnimationSwiperIndex: curSwiperIndex,
        attachVideoIsPlaying: false
      },()=>{
        // 获取视频点赞和收藏状态
        this.getVideoClickStatus()
        this.getVideoFavStatus()
        
      })
      // 初始化新页面的页面的变量
      
      this.initCurPageVar()

    },
    cancelRequest(){
      
      if(requestTask){
        requestTask.abort()
        requestTask = null
        console.log('cancelRequest success')
      }
    },
    swiperChange: function (e) {
      
      let curSwiperIndex = e.detail.current
      console.log('swiperChange curSwiperIndex:',curSwiperIndex)
      // curSwiperIndex 为滑动结束后的索引值，开启circular循环后，curSwiperIndex 会在0 1 2之间循环
      let _lastSwiperIndex = this.data._lastSwiperIndex
      const diff = curSwiperIndex - _lastSwiperIndex
      // console.log('_lastSwiperIndex:',_lastSwiperIndex)
      // console.log('diff:',diff)
      // 用户没动
      if (diff === 0) {
        console.log('swiperChange return')
        return
      }
      clearTimeout(aiOptimizeTimeHandler)
      this.cancelRequest()
      this.hideQuestionAttachContent()
      // 开始滑动，就暂停所有播放的语音
      this.stopAudio()
      // 更新
      this.setData({
        _lastSwiperIndex: curSwiperIndex,
        curSwiperIndex: curSwiperIndex,
        isGiveTheUp: false,
        isFav: false,
        _videoWatched: 0,
        chatPartVisible: false,
        curAiAudioDuration:0,
        isMuted: this.data.attachContentVisible
      })
      let _videoList = this.data._videoList
      // 初始化更新状态的调用
      canInvokeTimeUpdateFn = true
      // 手指滑动的方向
      const direction = diff === 1 || diff === -2 ? 'up' : 'down'
      let _curVideoIndex = this.data._curVideoIndex
      // console.log('direction:',direction)
      if (direction === 'down') {
        _curVideoIndex = _curVideoIndex - 1
      } else if (direction === 'up') {
        _curVideoIndex = _curVideoIndex + 1
      }
      if(_curVideoIndex > _videoList.length - 1){
        _curVideoIndex = 0
      }
      if(_curVideoIndex < 0){
        _curVideoIndex = _videoList.length - 1
      }
      
      // console.log('swiperChange _curVideoIndex:',_curVideoIndex)
      
      // console.log('_videoList:',this.data._videoList)
      // console.log('curSwiperIndex:',curSwiperIndex)
      // _curVideoIndex 有可能会超过videoList的数据范围
      this.setData({
        _curVideoIndex: _curVideoIndex
      })

      // if(_curVideoIndex > _videoList.length - 1){
      //   _curVideoIndex = 0
      // }
      // if(_curVideoIndex < 0){
      //   _curVideoIndex = _videoList.length - 1
      // }
      
      // 视频列表
      // let preVideoIndex = _curVideoIndex - 1
      // let nextVideoIndex = _curVideoIndex + 1
      // if (preVideoIndex < 0) {
      //   preVideoIndex = _videoList.length - 1
      // }
      // if (nextVideoIndex > _videoList.length - 1) {
      //   nextVideoIndex = 0
      // }
      // console.log('_curVideoIndex:',_curVideoIndex)
      // console.log('preVideoIndex:',preVideoIndex)
      // console.log('nextVideoIndex:',nextVideoIndex)
      
      // console.log('swiperChange:', _curVideoIndex)

      
    },
    getSettingStatus(){
      let that = this
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.record']) {
            that.setData({
              hasRecordAuth: true
            })
            // 初始化录音器
            this.initRecordManager()
          } else {
            that.setData({
              hasRecordAuth: false
            })
          }
        }
      })
    },
    // 获取麦克风权限
    getRecordAuth() {
      console.log('getRecordAuth')
      let that = this
      // 获取麦克风权限
      getAuthSetting(
        'scope.record',
        () => {
          that.setData({
            hasRecordAuth: true
          })
          // 初始化录音器
          this.initRecordManager()
        },
        () => {
          openSettingModal('提示', '请先开启麦克风权限', '去开通')
        }
      )
    },
    metedVideo() {
      // console.log('metedVideo')
      // 静音
      this.setData({
        isMuted: true
      })
      
    },
    stopAllAudioAndVideo(){
      this.stopAudio()
      this.stopCurSwiperVideo()
      this.stopAttachVideo()
    },
    stopAllAudio(){
      // 静音
      this.metedVideo()
      this.stopAudio()
    },
    recoverMuted(){
      console.log('recoverMuted')
      this.setData({
        isMuted: false
      })
    },
    recoverAttachMuted(){
      console.log('recoverAttachMuted')
      this.setData({
        isAttachVideoMuted: false
      })
    },
    addRecordConCurrent() {
      // 添加录音并发 1=正常 2=已达上限
      return new Promise((resolve) => {
        request({
          url: '/records/add-real-time?key=' + wx.getStorageSync('openid'),
          method: 'post',
          success(data) {
            // 1=正常 2=已达上限
            if (data.status === 1) {
              // 可以实时录音
              resolve(true)
            } else {
              resolve(false)
            }
          },
          fail() {
            resolve(false)
          }
        })
      })
    },
    async getAliStsToken() {
      console.log('getAliStsToken')
      let token = await getToken(AKID, AKKEY)
      // console.log('getAliStsToken:',token)
      this.setData(
        {
          _aliToken: token
        },
        () => {
          this.initSpeechTranscription()
        }
      )
    },
    async initSpeechTranscription() {
      // console.log('initSpeechTranscription st:',st)
      // if (st) {
      //   return
      // }
  
      st = new SpeechTranscription({
        url: aliSpeechUrl,
        appkey: APPKEY,
        token: this.data._aliToken
      })
  
      st.on('started', (msg) => {
        // console.log('Client recv started',msg)
        // this.setData({
        //   stResult: msg
        // })
        
      })
  
      st.on('changed', (res) => {
        // console.log('Client recv changed:', res)
        if (res) {
          try {
            let resObj = JSON.parse(res)
            // console.log('changed resObj:',resObj)
            if (resObj.payload) {
              // that.setData({
              //   tempStResult: resObj.payload.result
              // })
              tempStResult = resObj.payload.result
            }
          } catch (error) {
            console.error(error)
          }
        }
      })
  
      st.on('completed', (msg) => {
        // console.log('Client recv completed:', msg)
        // this.setData({
        //   stResult: msg
        // })
      })
  
      st.on('begin', (res) => {
        // console.log('st begin')
        // 句子开始
        // console.log('Client recv sentenceBegin:', res)
        stsFinished = false
      })
  
      st.on('end', (res) => {
        // console.log('Client recv sentenceEnd:', res)
        // 一句话结束
        // this.setData({
        //   stResult: msg
        // })
        // console.log('st end')
        stsFinished = true
        if (res) {
          try {
            let resObj = JSON.parse(res)
            // console.log('end Obj:',resObj)
            if (resObj.payload) {
              // that.setData({
              //   stResult: that.data.stResult + resObj.payload.result
              // })
              // console.log('end stResult:',stResult)
              // console.log('resObj.payload.result:',resObj.payload.result)
              let newResult = stResult + resObj.payload.result
              // console.log('newResult:',newResult)
              stResult = newResult
              // that.setData({
              //     stResult: newResult
              //   },()=>{
              //     console.log('end stResult2:',that.data.stResult)
              //   })
            }
          } catch (error) {
            console.error(error)
          }
        }
      })
  
      st.on('closed', () => {
        console.log('Client recv closed')
      })
  
      st.on('failed', (msg) => {
        // console.log('Client recv failed:', msg)
        // this.setData({
        //   stResult: msg
        // })
      })
    },
    startCountTime() {
      let that = this
      if (timeHander) {
        clearInterval(timeHander)
      }
      curSeconds = 0
      timeHander = setInterval(() => {
        curSeconds++
        // console.log('curSeconds:',curSeconds)
        if (curSeconds >= topTotalSeconds) {
          clearInterval(timeHander)
          that.recordFinish()
          that.setData({
            submitBtnBgWidth: '100%',
            curTimeStr: formatSeconds(topTotalSeconds)
          })
        } else {
          if (topTotalSeconds - curSeconds <= 10) {
            let countTimeNum = this.data.countTimeNum - 1
            this.setData({
              showPureTime: false,
              countTimeNum
            })
          }
          that.setData({
            submitBtnBgWidth:
              Math.floor((curSeconds / topTotalSeconds) * 100) + '%',
            curTimeStr: formatSeconds(curSeconds)
          })
        }
      }, 1000)
    },
    async startRealTimeRecord() {
      // 开始录音
  
      if (!this.data._aliToken) {
        await this.getAliStsToken()
      }
      // 开始录音
      if (!st) {
        this.initSpeechTranscription()
      }
      // console.log('startRealTimeRecord recorderManager:',recorderManager)
      if (!recorderManager) {
        this.initRecordManager()
      }
  
      //
      // console.log('_inRecord:',this.data._inRecord)
      if (!this.data._inRecord) {
        console.log('startRealTimeRecord _inRecord 点击太快')
        // 正在记录，避免重复打开多次
        return
      }
      console.log('开始实时录音')
      this.showRecordPop()
  
      this.initRecordState()
      this.startCountTime()
      let defaultStartParams = st.defaultStartParams()
      // console.log('defaultStartParams:',defaultStartParams)
      try {
        await st.start(defaultStartParams)  
      } catch (error) {
        console.log('startRealTimeRecord error:',error)
      }
      
      // console.log('topTotalSeconds:',topTotalSeconds)
      recorderManager.start({
        duration: topTotalSeconds * 1000,
        sampleRate: 16000,
        format: 'mp3',
        frameSize: 4,
        encodeBitRate: 96000,
        numberOfChannels: 1
      })
    },
    async authRecord() {
      
      
      if (!this.data._inRecord) {
        // console.log('authRecord')
        clearTimeout(touchStartTimer)
        touchStartTimer = setTimeout(async () => {
          this.stopAllAudio()
          this.playAudio('https://wanhuhealth.oss-cn-beijing.aliyuncs.com/static/mini-douwei/longpresson.mp3','tip')
          // console.log('timeout authRecord')
          // 先不管并发
          // let canRealTimeRecord = await this.addRecordConCurrent()
          let canRealTimeRecord = true
          // canRealTimeRecord = false
          if (canRealTimeRecord) {
            this.setData({
              _recordType: 1,
              _inRecord: true,
            },()=>{
              clearTimeout(startRecordTimer)
              startRecordTimer = setTimeout(()=>{
                this.startRealTimeRecord()
              },100)
              
            })
            
          } else {
            
            this.setData({
              _recordType: 2,
              _inRecord: true,
            },()=>{
              clearTimeout(startRecordTimer)
              startRecordTimer = setTimeout(()=>{
                this.startRecordFile()
              },100)
            })
          }
          // 设置overflow 禁止页面滚动
          try {
            // @ts-ignore
            wx.setPageStyle({
              style: {
                overflow: 'hidden' // ‘auto’
              }
           })
          } catch (error) {
            
          }
          
  
        }, 600)
      }
    },
    cancelAuthRecord() {
      console.log('cancelAuthRecord')
      clearTimeout(touchStartTimer)
      this.hideRecordPop()
      if(recorderManager){
        recorderManager.stop()
      }
      
    },
  }
})
